package com.fypg.module.medical.service.auth;

import cn.hutool.core.lang.Assert;
import com.fypg.framework.common.biz.system.oauth2.OAuth2TokenCommonApi;
import com.fypg.framework.common.biz.system.oauth2.dto.OAuth2AccessTokenCreateReqDTO;
import com.fypg.framework.common.biz.system.oauth2.dto.OAuth2AccessTokenRespDTO;
import com.fypg.framework.common.enums.CommonStatusEnum;
import com.fypg.framework.common.enums.TerminalEnum;
import com.fypg.framework.common.enums.UserTypeEnum;
import com.fypg.framework.common.util.monitor.TracerUtils;
import com.fypg.framework.common.util.servlet.ServletUtils;
import com.fypg.module.medical.controller.app.auth.vo.AppAuthLoginRespVO;
import com.fypg.module.medical.controller.app.auth.vo.AppAuthWeixinMiniAppLoginReqVO;
import com.fypg.module.medical.convert.auth.AuthConvert;
import com.fypg.module.medical.dal.dataobject.user.MemberUserDO;
import com.fypg.module.medical.service.user.MemberUserService;
import com.fypg.module.system.api.logger.LoginLogApi;
import com.fypg.module.system.api.logger.dto.LoginLogCreateReqDTO;
import com.fypg.module.system.api.sms.SmsCodeApi;
import com.fypg.module.system.api.social.SocialClientApi;
import com.fypg.module.system.api.social.SocialUserApi;
import com.fypg.module.system.api.social.dto.SocialUserBindReqDTO;
import com.fypg.module.system.api.social.dto.SocialUserRespDTO;
import com.fypg.module.system.api.social.dto.SocialWxPhoneNumberInfoRespDTO;
import com.fypg.module.system.enums.logger.LoginLogTypeEnum;
import com.fypg.module.system.enums.logger.LoginResultEnum;
import com.fypg.module.system.enums.oauth2.OAuth2ClientConstants;
import com.fypg.module.system.enums.sms.SmsSceneEnum;
import com.fypg.module.system.enums.social.SocialTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

import static com.fypg.framework.common.util.servlet.ServletUtils.getClientIP;

/**
 * 会员的认证 Service 接口
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class MemberAuthServiceImpl implements MemberAuthService {

    @Resource
    private MemberUserService userService;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private LoginLogApi loginLogApi;
    @Resource
    private SocialUserApi socialUserApi;
    @Resource
    private SocialClientApi socialClientApi;
    @Resource
    private OAuth2TokenCommonApi oauth2TokenApi;



    @Override
    public AppAuthLoginRespVO weixinMiniAppLogin(AppAuthWeixinMiniAppLoginReqVO reqVO) {
        // 获得对应的手机号信息
        SocialWxPhoneNumberInfoRespDTO phoneNumberInfo = socialClientApi.getWxMaPhoneNumberInfo(
                UserTypeEnum.MEMBER.getValue(), reqVO.getPhoneCode());
        Assert.notNull(phoneNumberInfo, "获得手机信息失败，结果为空");

        // 获得获得注册用户
        MemberUserDO user = userService.createUserIfAbsent(phoneNumberInfo.getPurePhoneNumber(),
                getClientIP(), TerminalEnum.WECHAT_MINI_PROGRAM.getTerminal());
        Assert.notNull(user, "获取用户失败，结果为空");

        // 绑定社交用户
        String openid = socialUserApi.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                SocialTypeEnum.WECHAT_MINI_PROGRAM.getType(), reqVO.getLoginCode(), reqVO.getState()));

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user, user.getMobile(), LoginLogTypeEnum.LOGIN_SOCIAL, openid);
    }

    private AppAuthLoginRespVO createTokenAfterLoginSuccess(MemberUserDO user, String mobile,
                                                            LoginLogTypeEnum logType, String openid) {
        // 插入登陆日志
        createLoginLog(user.getId(), mobile, logType, LoginResultEnum.SUCCESS);
        // 创建 Token 令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(new OAuth2AccessTokenCreateReqDTO()
                .setUserId(user.getId()).setUserType(getUserType().getValue())
                .setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT));
        // 构建返回结果
        return AuthConvert.INSTANCE.convert(accessTokenRespDTO, openid);
    }

    private void createLoginLog(Long userId, String mobile, LoginLogTypeEnum logType, LoginResultEnum loginResult) {
        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logType.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userId);
        reqDTO.setUserType(getUserType().getValue());
        reqDTO.setUsername(mobile);
        reqDTO.setUserAgent(ServletUtils.getUserAgent());
        reqDTO.setUserIp(getClientIP());
        reqDTO.setResult(loginResult.getResult());
        loginLogApi.createLoginLog(reqDTO);
        // 更新最后登录时间
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
            userService.updateUserLogin(userId, getClientIP());
        }
    }

    @Override
    public AppAuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenRespDTO accessTokenDO = oauth2TokenApi.refreshAccessToken(refreshToken,
                OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return AuthConvert.INSTANCE.convert(accessTokenDO, null);
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.MEMBER;
    }

}
